##################
# UDP服务端
# 实现一个简单都四则运算计算器
##################

from socket import *
import re

# 定义常量
PORT = 12000
pattern = r'(\d+)(\+|\-|\*|\/)(\d+)'


# 定义方法
def parse_data(data: str) -> tuple:
    matcher = re.match(pattern, data)
    return matcher.group(1), matcher.group(2), matcher.group(3)


def calc_data(left: int, op: str, right: int) -> int:
    left = int(left)
    right = int(right)
    if op == '+':
        return left + right
    elif op == '-':
        return left - right
    elif op == '*':
        return left * right
    elif op == '/':
        return int(left / right)
    return -1


sock = socket(AF_INET, SOCK_DGRAM)
sock.bind(('', PORT))
print('The server is ready to receive')
while True:
    clientData, clientAddr = sock.recvfrom(2048)
    l, op, r = parse_data(clientData.decode())
    result = calc_data(l, op, r)
    sock.sendto(str(result).encode(), clientAddr)